﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

class TiffImageSplitter
{
    // Retrive PageCount of a multi-page tiff image
    public static int GetPageCount(String fileName)
    {
        int pageCount = -1;
        using(Image img = Bitmap.FromFile(fileName))
        {
            pageCount = img.GetFrameCount(FrameDimension.Page);
            img.Dispose();
        }
        return pageCount;
    }

    public static int GetPageCount(Image img)
    {
        int pageCount = -1;
        pageCount = img.GetFrameCount(FrameDimension.Page);

        return pageCount;
    }

    // Retrive a specific Page from a multi-page tiff image
    public static Image GetTiffImage(String sourceFile, int pageNumber)
    {
        using (Image sourceIamge = Bitmap.FromFile(sourceFile))
        {
            return GetTiffImage(sourceIamge, pageNumber);
        }
    }

    public static Image GetTiffImage(Image sourceImage, int pageNumber)
    {
        MemoryStream ms = new MemoryStream();
        Image returnImage = null;

        Guid objGuid = sourceImage.FrameDimensionsList[0];
        FrameDimension objDimension = new FrameDimension(objGuid);
        sourceImage.SelectActiveFrame(objDimension, pageNumber);
        sourceImage.Save(ms, ImageFormat.Tiff);
        returnImage = Image.FromStream(ms);

        return returnImage;
    }
}
